package com.sqllite.springbootsqlitejdbc.controller;

import com.sqllite.springbootsqlitejdbc.bean.User;
import com.sqllite.springbootsqlitejdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 创建用户
    @PostMapping
    public ResponseEntity<String> createUser(@RequestParam String name, @RequestParam String email) {
        int result = userService.createUser(name, email);
        return result > 0 ? ResponseEntity.ok("User created successfully.") : ResponseEntity.badRequest().body("Failed to create user.");
    }

    // 查询所有用户
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
    }

    // 更新用户
    @PutMapping("/{id}")
    public ResponseEntity<String> updateUser(@PathVariable Long id, @RequestParam String name, @RequestParam String email) {
        int result = userService.updateUser(id, name, email);
        return result > 0 ? ResponseEntity.ok("User updated successfully.") : ResponseEntity.badRequest().body("Failed to update user.");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Long id) {
        int result = userService.deleteUser(id);
        return result > 0 ? ResponseEntity.ok("User deleted successfully.") : ResponseEntity.badRequest().body("Failed to delete user.");
    }
}
